<template>
  <div class="material-product-container">
    <!-- 左侧树形菜单 -->
    <div class="left-tree">
      <el-input
        v-model="searchText"
        placeholder="请输入分类名称"
        prefix-icon="Search"
        clearable
        class="search-input"
        @clear="resetCategory"
      />
      <el-tree
        ref="treeRef"
        :data="categoryTreeData"
        :props="{
          label: 'label',
          children: 'children'
        }"
        node-key="id"
        highlight-current
        :expand-on-click-node="false"
        :default-expand-all="true"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      >
        <template #default="scope">
          <span>{{ scope.data.label }}</span>
          <span v-if="scope.data.children && scope.data.children.length" style="color: #999">
            ({{ scope.data.children.length }})
          </span>
        </template>
      </el-tree>
    </div>

    <!-- 右侧表格内容 -->
    <div class="right-content">
      <!-- 添加控制按钮 -->
      <div class="control-buttons">
        <el-tooltip content="显示/隐藏搜索" placement="top">
          <el-button :icon="Search" circle @click="toggleSearch" />
        </el-tooltip>
        <el-tooltip content="刷新" placement="top">
          <el-button :icon="Refresh" circle @click="refreshPage" />
        </el-tooltip>
        <el-tooltip content="显示/隐藏列" placement="top">
          <el-button :icon="Grid" circle @click="showColumnDialog" />
        </el-tooltip>
      </div>

      <!-- 搜索表单 -->
      <div class="search-form" v-show="isSearchVisible">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="物料编码">
            <el-input
              v-model="searchForm.materialCode"
              placeholder="请输入物料编码"
              clearable
              @keyup.enter="handleSearch"
              @clear="handleReset"
            />
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input
              v-model="searchForm.materialName"
              placeholder="请输入物料名称"
              clearable
              @keyup.enter="handleSearch"
              @clear="handleReset"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="operation-bar">
        <el-button class="custom-button" type="primary" plain @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增
        </el-button>
        <el-button class="custom-button" type="success" plain @click="handleEdit">
          <el-icon><Edit /></el-icon> 修改
        </el-button>
        <el-button class="custom-button" type="danger" plain @click="handleBatchDelete">
          <el-icon><Delete /></el-icon> 删除
        </el-button>
        <el-button class="custom-button" type="info" plain>
          <el-icon><Upload /></el-icon> 导入
        </el-button>
        <el-button class="custom-button" type="warning" plain>
          <el-icon><Download /></el-icon> 导出
        </el-button>
      </div>

      <el-table ref="mainTableRef" :data="tableData" row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="物料编码" align="center">
          <template #default="scope">
            <a 
              href="javascript:;" 
              class="material-code-link"
              @click="handleViewDetail(scope.row)"
            >
              {{ scope.row.materialCode }}
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="materialName" label="物料名称" align="center" />
        <el-table-column prop="specification" label="规格型号" align="center" />
        <el-table-column prop="flats" label="单位" align="center" />
        <el-table-column label="所属分类" align="center">
          <template #default="scope">
            {{ getCategoryName(scope.row.flatsMaterial) }}
          </template>
        </el-table-column>
        <el-table-column label="是否启用" align="center">
          <template #default="scope">
            <div style="display: flex; justify-content: space-between; align-items: center">
              <span :style="{ color: scope.row.isLock === 0 ? '#409eff' : '#999' }">否</span>
              <el-switch
                v-model="scope.row.isLock"
                :active-value="1"
                :inactive-value="0"
                @change="(val) => handleEnableChange(val, scope.row)"
              />
              <span :style="{ color: scope.row.isLock === 1 ? '#409eff' : '#999' }">是</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="设置安全库存" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.safetyStock == 1 ? 'primary' : 'danger'"
              effect="plain"
              class="safety-stock-tag"
            >
              {{ scope.row.safetyStock == 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="descs" label="备注" align="center" />
        <el-table-column fixed="right" label="操作列" min-width="120">
          <template #default="scope">
            <div class="operation-buttons">
              <template v-if="scope.row.isLock === 0">
                <el-button link type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
                <el-button link type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button>
                <el-button link type="primary" size="small">标签打印</el-button>
              </template>
              <template v-else>
                <el-button link type="primary" size="small">标签打印</el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 修改分页组件 -->
      <div class="pagination-container">
        <span class="total-text">共 {{ pagination.total }} 条</span>
        <div class="page-size-selector">
          <el-select v-model="pagination.pageSize" style="width: 100px">
            <el-option
              v-for="size in pagination.pageSizes"
              :key="size"
              :label="`${size}条/页`"
              :value="size"
            />
          </el-select>
        </div>
        <div class="custom-pagination">
          <button 
            class="page-btn" 
            :disabled="pagination.currentPage === 1"
            @click="handleFirstPage"
          >
            首页
          </button>
          <button 
            class="page-btn" 
            :disabled="pagination.currentPage === 1"
            @click="handlePrevPage"
          >
            上一页
          </button>
          <div class="page-numbers">
            <button
              v-for="page in displayPages"
              :key="page"
              class="page-btn"
              :class="{ active: page === pagination.currentPage }"
              @click="handleCurrentChange(page)"
            >
              {{ page }}
            </button>
          </div>
          <button 
            class="page-btn" 
            :disabled="pagination.currentPage === totalPages"
            @click="handleNextPage"
          >
            下一页
          </button>
          <button 
            class="page-btn" 
            :disabled="pagination.currentPage === totalPages"
            @click="handleLastPage"
          >
            尾页
          </button>
        </div>
        <div class="page-jump">
          <span class="text">前往</span>
          <el-input
            v-model="jumpPage"
            class="jump-input"
            :placeholder="pagination.currentPage"
            @keyup.enter="handleJumpPage"
          />
          <span class="text">页</span>
        </div>
      </div>
    </div>
  </div>

  <!-- 新增对话框 -->
  <el-dialog v-model="dialogFormVisible" title="新增物料/产品" width="800">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料编码" prop="materialCode" required>
            <div style="display: flex; align-items: center;">
              <el-input v-model="form.materialCode" placeholder="请输入物料编码" :disabled="form.autoGenerate" />
              <div class="auto-generate-switch">
                <el-switch 
                  v-model="form.autoGenerate" 
                  class="ml-2" 
                  style="margin-left: 10px;"
                />
                <div class="auto-generate-text">
                  <span>自</span>
                  <span>动</span>
                  <span>生</span>
                  <span>成</span>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料名称" prop="materialName" required>
            <el-input v-model="form.materialName" placeholder="请输入物料名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规格型号">
            <el-input v-model="form.specification" placeholder="请输入规格型号" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="单位" prop="flats" required>
            <el-select v-model="form.flats" placeholder="请选择单位" style="width: 100%">
              <el-option
                v-for="item in filteredUnitOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料/产品分类" prop="flatsMaterial" required>
            <el-tree-select
              v-model="form.flatsMaterial"
              :data="categoryTreeData"
              :props="{
                label: 'label',
                children: 'children',
                value: 'id'
              }"
              :render-after-expand="false"
              check-strictly
              placeholder="请选择所属分类"
              style="width: 100%"
              clearable
              filterable
            >
              <template #default="scope">
                <span>{{ scope.data.label }}</span>
                <span v-if="scope.data.children && scope.data.children.length" style="color: #999">
                  ({{ scope.data.children.length }})
                </span>
              </template>
            </el-tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="高价值/易被盗物品">
            <el-checkbox/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="是否启用">
            <div style="display: flex; align-items: center;">
              <span style="color: #999; margin-right: 4px;">否</span>
              <el-switch 
                v-model="form.isLock"
                :active-value="1"
                :inactive-value="0"
              />
              <span style="color: #409EFF; margin-left: 4px;">是</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批次管理">
            <div style="display: flex; align-items: center;">
              <span style="color: #999; margin-right: 4px;">否</span>
              <el-switch 
                v-model="form.isBatch"
                :active-value="1"
                :inactive-value="0"
              />
              <span style="color: #409EFF; margin-left: 4px;">是</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="安全库存">
            <div style="display: flex; align-items: center;">
              <span style="color: #999; margin-right: 4px;">否</span>
              <el-switch 
                v-model="form.safetyStock"
                :active-value="1"
                :inactive-value="0"
              />
              <span style="color: #409EFF; margin-left: 4px;">是</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.descs" type="textarea" :rows="3" placeholder="请输入内容" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveMaterialProduct">确定</el-button>
        <el-button @click="dialogFormVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 查看详情对话框 -->
  <el-dialog v-model="detailDialogVisible" title="查看详情" width="800">
    <el-form :model="detailForm" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料编码">
            <el-input v-model="detailForm.materialCode" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料名称">
            <el-input v-model="detailForm.materialName" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规格型号">
            <el-input v-model="detailForm.specification" type="textarea" :rows="2" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="单位">
            <el-input v-model="detailForm.flats" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料/产品分类">
            <el-input :value="getCategoryName(detailForm.flatsMaterial)" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="高价值/易被盗物品">
            <el-checkbox v-model="detailForm.isHighValue" disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="是否启用">
            <el-radio-group v-model="detailForm.isLock" disabled>
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批次管理">
            <div style="display: flex; align-items: center;">
              <span :style="{ color: detailForm.isBatch === 0 ? '#409eff' : '#999' }">否</span>
              <el-switch 
                v-model="detailForm.isBatch"
                :active-value="1"
                :inactive-value="0"
                disabled
              />
              <span :style="{ color: detailForm.isBatch === 1 ? '#409eff' : '#999' }">是</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="安全库存">
            <el-radio-group v-model="detailForm.safetyStock" disabled>
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="detailForm.descs" type="textarea" :rows="3" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改对话框 -->
  <el-dialog v-model="editDialogVisible" title="修改物料/产品" width="800">
    <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料编码" prop="materialCode">
            <el-input v-model="editForm.materialCode" placeholder="请输入物料编码" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料名称" prop="materialName" required>
            <el-input v-model="editForm.materialName" placeholder="请输入物料名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规格型号">
            <el-input v-model="editForm.specification" placeholder="请输入规格型号" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="单位" prop="flats" required>
            <el-select v-model="editForm.flats" placeholder="请选择单位" style="width: 100%">
              <el-option
                v-for="item in filteredUnitOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料/产品分类" prop="flatsMaterial" required>
            <el-tree-select
              v-model="editForm.flatsMaterial"
              :data="categoryTreeData"
              :props="{
                label: 'label',
                children: 'children',
                value: 'id'
              }"
              :render-after-expand="false"
              check-strictly
              placeholder="请选择所属分类"
              style="width: 100%"
              clearable
              filterable
            >
              <template #default="scope">
                <span>{{ scope.data.label }}</span>
                <span v-if="scope.data.children && scope.data.children.length" style="color: #999">
                  ({{ scope.data.children.length }})
                </span>
              </template>
            </el-tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="高价值/易被盗物品">
            <el-switch
              v-model="editForm.isHighValue"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="是否启用">
            <el-radio-group v-model="editForm.isLock" disabled>
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批次管理">
            <div style="display: flex; align-items: center;">
              <span :style="{ color: editForm.isBatch === 0 ? '#409eff' : '#999' }">否</span>
              <el-switch 
                v-model="editForm.isBatch"
                :active-value="1"
                :inactive-value="0"
              />
              <span :style="{ color: editForm.isBatch === 1 ? '#409eff' : '#999' }">是</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="安全库存">
            <el-radio-group v-model="editForm.safetyStock">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input 
              v-model="editForm.descs" 
              type="textarea" 
              :rows="3" 
              placeholder="请输入内容"
              @input="(val) => {
                console.log('备注输入:', val)
                editForm.descs = val
              }"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveEditMaterialProduct">确定</el-button>
        <el-button @click="editDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 列显示设置对话框 -->
  <el-dialog
    v-model="columnDialogVisible"
    title="显示/隐藏"
    width="600px"
    destroy-on-close
  >
    <div class="column-dialog-content">
      <el-tree
        ref="columnTreeRef"
        :data="categoryTreeData"
        :props="{
          label: 'label',
          children: 'children'
        }"
        node-key="id"
        highlight-current
        :expand-on-click-node="false"
        :default-expand-all="true"
        @node-click="handleColumnTreeNodeClick"
      />
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import http from '@/api/http'
import { ElMessageBox, ElMessage } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Grid,
  ArrowLeft,
  ArrowRight,
  Plus, 
  Edit, 
  Delete, 
  Upload, 
  Download 
} from '@element-plus/icons-vue'

// Constants
const API_ENDPOINTS = {
  GET_MATERIAL_PRODUCT: '/api/MaterialProduct/GetMaterialProduct',
  ADD_MATERIAL_PRODUCT: '/api/MaterialProduct/AddMaterialProduct',
  DELETE_MATERIAL_PRODUCT: 'api/MaterialProduct/DeleteMaterialProduct',
  BATCH_DELETE: '/api/MaterialProduct/BatchDelete',
  GET_MATERIAL_CATALOG: '/api/MaterialCatalog/GetMaterialCatalog',
  UPDATE_MATERIAL_PRODUCT: '/api/MaterialProduct/UpdateMaterialProduct'
}

const INITIAL_FORM_STATE = {
  id: 0,
  materialCode: '',
  materialName: '',
  specification: '',
  flats: '',
  flatsMaterial: '',
  isHighValue: 0,
  isLock: 0,
  isBatch: 0,
  safetyStock: 0,
  descs: '',
  materialImg: '',
  autoGenerate: false
}

const UNIT_OPTIONS = [
  { value: '微米1', label: '微米1' },
  { value: '公支', label: '公支' },
  { value: '英支', label: '英支' },
  { value: '匹', label: '匹' },
  { value: '捆', label: '捆' },
  { value: '层', label: '层' },
  { value: '套', label: '套' },
  { value: 'N.m', label: 'N.m' },
  { value: 'Kw', label: 'Kw' },
  { value: 'min', label: 'min' },
  { value: '欧', label: '欧' },
  { value: 'V', label: 'V' },
  { value: 'm/s', label: 'm/s' },
  { value: 'mV', label: 'mV' },
  { value: 'Mpa', label: 'Mpa' },
  { value: 'Hz', label: 'Hz' },
  { value: '卷', label: '卷' },
  { value: '那台应用', label: '那台应用' },
  { value: '欧姆', label: '欧姆' },
  { value: 'f', label: 'f' },
  { value: '和', label: '和' },
  { value: 'pcs', label: 'pcs' },
  { value: '千克', label: '千克' },
  { value: '个', label: '个' },
  { value: '米', label: '米' },
  { value: '公里', label: '公里' },
  { value: '粒', label: '粒' },
  { value: '戒', label: '戒' },
  { value: '张', label: '张' },
  { value: '台', label: '台' },
  { value: '件', label: '件' },
  { value: '资料单位-包', label: '资料单位-包' },
  { value: '块', label: '块' },
  { value: '毫升', label: '毫升' },
  { value: '升', label: '升' },
  { value: '克', label: '克' },
  { value: '批', label: '批' },
  { value: '笼', label: '笼' },
  { value: 'KG', label: 'KG' },
  { value: '立方米', label: '立方米' }
]

// Form validation rules
const rules = {
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  flats: [{ required: true, message: '请选择单位', trigger: 'change' }],
  flatsMaterial: [{ required: true, message: '请选择物料/产品分类', trigger: 'change' }]
}

// Refs and reactive state
const tableData = ref([])
const multipleSelection = ref([])
const mainTableRef = ref(null)
const currentCategoryId = ref('')
const dialogFormVisible = ref(false)
const detailDialogVisible = ref(false)
const editDialogVisible = ref(false)
const formRef = ref(null)
const categoryTreeData = ref([])
const searchText = ref('')
const treeRef = ref(null)

// 添加搜索和分页相关的响应式数据
const searchForm = reactive({
  materialCode: '',
  materialName: '',
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100]
})

// Form state
const form = reactive({...INITIAL_FORM_STATE})
const detailForm = reactive({...INITIAL_FORM_STATE})
const editForm = reactive({
  id: 0,
  materialCode: '',
  materialName: '',
  specification: '',
  flats: '',
  flatsMaterial: '',
  isHighValue: 0,
  isLock: 0,
  isBatch: 0,
  safetyStock: 0,
  descs: '',
  materialImg: ''
})
const editFormRef = ref(null)

// Computed properties
const filteredUnitOptions = computed(() => {
  const searchQuery = form.flats?.toLowerCase() || ''
  return UNIT_OPTIONS.filter(option => 
    option.label.toLowerCase().includes(searchQuery) || 
    option.value.toLowerCase().includes(searchQuery)
  )
})

// 添加跳转页码的响应式变量
const jumpPage = ref('')

// 计算总页数
const totalPages = computed(() => Math.ceil(pagination.total / pagination.pageSize))

// 计算要显示的页码
const displayPages = computed(() => {
  const current = pagination.currentPage
  const total = totalPages.value
  const max = 7 // 最多显示的页码数
  
  if (total <= max) {
    return Array.from({ length: total }, (_, i) => i + 1)
  }
  
  let start = Math.max(current - Math.floor(max / 2), 1)
  let end = start + max - 1
  
  if (end > total) {
    end = total
    start = Math.max(end - max + 1, 1)
  }
  
  return Array.from({ length: end - start + 1 }, (_, i) => start + i)
})

// Utility functions
const handleApiResponse = (response, successMessage = '操作成功') => {
  if (response.status === true || response === true || response === 1 || 
      (response.data && response.data.success)) {
    ElMessage.success(successMessage)
    return true
  }
  throw new Error(response.message || '操作失败')
}

const handleApiError = (error, errorMessage = '操作失败') => {
  console.error(errorMessage + ':', error)
  ElMessage.error(error.message || errorMessage)
  return false
}

// Data loading functions
const loadTableData = async () => {
  try {
    let url = API_ENDPOINTS.GET_MATERIAL_PRODUCT

    // 构建查询参数
    const queryParams = new URLSearchParams()
    
    // 添加分页参数
    queryParams.append('pageIndex', pagination.currentPage.toString())
    queryParams.append('pageSize', pagination.pageSize.toString())
    
    // 添加搜索参数
    if (searchForm.materialCode) {
      queryParams.append('materialCode', searchForm.materialCode.trim())
    }
    if (searchForm.materialName) {
      queryParams.append('materialName', searchForm.materialName.trim())
    }
    
    // 添加分类ID
    if (currentCategoryId.value) {
      queryParams.append('flatsMaterial', currentCategoryId.value)
    }

    url += `?${queryParams.toString()}`
    console.log('发送请求URL:', url)
    
    const response = await http.get(url)
    console.log('服务器响应数据:', response)
    
    if (response && response.data) {
      // 如果选中了分类，只显示该分类的数据
      if (currentCategoryId.value) {
        const filteredData = response.data.products.filter(item => 
          String(item.flatsMaterial) === String(currentCategoryId.value)
        )
        tableData.value = filteredData
        pagination.total = filteredData.length
      } else {
        // 如果没有选中分类，显示所有数据
        tableData.value = response.data.products || []
        pagination.total = response.data.totalCount || 0
      }
      if (mainTableRef.value) {
        mainTableRef.value.clearSelection();
      }
      multipleSelection.value = [] // 刷新数据后清空多选
      console.log('过滤后的数据:', {
        当前分类ID: currentCategoryId.value,
        数据条数: tableData.value.length,
        总条数: pagination.total
      })
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    pagination.total = 0
  }
}

const getCategoryTree = async () => {
  try {
    const response = await http.get(API_ENDPOINTS.GET_MATERIAL_CATALOG)
    console.log('API返回的原始数据:', response) // 添加日志
    if (response.status === true && response.data) {
      // 确保数据格式正确
      const formatTreeData = (data) => {
        if (!Array.isArray(data)) {
          console.warn('输入数据不是数组:', data)
          return []
        }
        return data.map(item => {
          const formattedItem = {
            id: item.id,
            label: item.label || item.name || item.title || '未命名', // 增加更多可能的名称字段
            children: []
          }
          if (Array.isArray(item.children) && item.children.length > 0) {
            formattedItem.children = formatTreeData(item.children)
          }
          return formattedItem
        })
      }
      
      const formattedData = formatTreeData(response.data)
      console.log('格式化后的树形数据:', formattedData) // 添加日志
      categoryTreeData.value = formattedData
    }
  } catch (error) {
    handleApiError(error, '获取分类数据失败')
  }
}

// CRUD operations
const saveMaterialProduct = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const saveData = {
      ...form,
      materialCode: form.materialCode || '',
      materialName: form.materialName || '',
      specification: form.specification || '',
      flats: form.flats || '',
      flatsMaterial: form.flatsMaterial || '',
      descs: form.descs || '',
      materialImg: ''
    }
    
    const response = await http.post(API_ENDPOINTS.ADD_MATERIAL_PRODUCT, saveData)
    if (handleApiResponse(response, '保存成功')) {
      dialogFormVisible.value = false
      materialProductList()
    }
  } catch (error) {
    handleApiError(error, '保存失败，请检查数据格式')
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除此记录?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const response = await http.get(`${API_ENDPOINTS.DELETE_MATERIAL_PRODUCT}?id=${row.id}`)
        if (handleApiResponse(response, '删除成功')) {
          materialProductList()
        }
      } catch (error) {
        handleApiError(error, '删除失败')
      }
    })
    .catch(() => {})
}

const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    return ElMessage.warning('请选择要删除的记录')
  }

  try {
    await ElMessageBox.confirm('确认删除选中的记录?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const ids = multipleSelection.value.map((item) => item.id)
    const response = await http.post(API_ENDPOINTS.BATCH_DELETE, { ids })
    
    if (handleApiResponse(response, '批量删除成功')) {
      materialProductList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      handleApiError(error, '批量删除失败')
    }
  }
}

const materialProductList = async () => {
  currentCategoryId.value = ''
  searchForm.materialCode = ''
  searchForm.materialName = ''
  pagination.currentPage = 1
  await loadTableData()
}

// 修改重置分类的方法
const resetCategory = async () => {
  console.log('重置分类')
  currentCategoryId.value = ''
  if (treeRef.value) {
    treeRef.value.setCurrentKey(null)
  }
  // 重置搜索条件和分页
  searchForm.materialCode = ''
  searchForm.materialName = ''
  pagination.currentPage = 1
  await loadTableData()
}

// 处理是否启用状态改变
const handleEnableChange = async (val, row) => {
  try {
    await http.post('/api/MaterialProduct/UpdateMaterialProduct', {
      id: row.id,
      isEnabled: val
    })
  } catch (error) {
    console.error('Error updating enabled status:', error)
    row.isEnabled = !val // 如果失败，恢复原状态
  }
}

// 处理多选变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection || []
  console.log('选中的数据:', multipleSelection.value)
}

// 打开新增对话框
const handleAdd = () => {
  dialogFormVisible.value = true
  resetForm()
}

// 重置表单方法
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    Object.assign(form, INITIAL_FORM_STATE)
  }
}

// Event handlers with debounce
let searchTimeout = null
const handleSearchInput = (value) => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => {
    searchText.value = value
  }, 300)
}

// Auto-generate material code
const generateMaterialCode = () => {
  const timestamp = Date.now()
  return `IF${timestamp}`.substring(0, 30)
}

// Watch for auto-generate changes
watch(() => form.autoGenerate, (newVal) => {
  if (newVal) {
    form.materialCode = generateMaterialCode()
  } else {
    form.materialCode = ''
  }
})

// Watch for search text changes with proper cleanup
watch(searchText, (val) => {
  treeRef.value?.filter(val)
}, { flush: 'post' })

// 树节点过滤方法
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase())
}

// 修改 handleNodeClick 方法
const handleNodeClick = async (data) => {
  console.log('点击的树节点:', data)
  currentCategoryId.value = data.id
  
  // 重置搜索条件和分页
  searchForm.materialCode = ''
  searchForm.materialName = ''
  pagination.currentPage = 1
  
  await loadTableData()
}

// 添加获取完整分类路径的方法
const getFullCategoryPath = (node) => {
  const path = []
  let currentNode = node
  
  while (currentNode) {
    path.unshift(currentNode.id)
    currentNode = findParentNode(currentNode)
  }
  
  return path
}

// 添加查找父节点的方法
const findParentNode = (node) => {
  const findParent = (data, targetId) => {
    for (const item of data) {
      if (item.children && item.children.some(child => child.id === targetId)) {
        return item
      }
      if (item.children) {
        const found = findParent(item.children, targetId)
        if (found) return found
      }
    }
    return null
  }
  
  return findParent(categoryTreeData.value, node.id)
}

// 添加响应式变量存储选中的分类路径
const selectedCategoryPath = ref([])

// 获取分类名称的方法
const getCategoryName = (categoryId) => {
  if (!categoryId) return ''
  
  // 转换categoryId为字符串进行比较
  const targetId = String(categoryId)
  
  // 递归查找函数
  const findCategory = (categories) => {
    if (!categories) return null
    
    for (const category of categories) {
      // 转换category.id为字符串进行比较
      if (String(category.id) === targetId) {
        return category.label
      }
      if (category.children && category.children.length > 0) {
        const found = findCategory(category.children)
        if (found) return found
      }
    }
    return null
  }
  
  const result = findCategory(categoryTreeData.value)
  return result || ''  // 如果没找到对应的分类名称，返回空字符串而不是ID
}

// 添加查看详情的方法
const handleViewDetail = (row) => {
  detailForm.id = Number(row.id || 0)
  detailForm.materialCode = row.materialCode || ''
  detailForm.materialName = row.materialName || ''
  detailForm.specification = row.specification || ''
  detailForm.flats = row.flats || ''
  detailForm.flatsMaterial = row.flatsMaterial || ''
  detailForm.isHighValue = Number(row.isHighValue || 0)
  detailForm.isLock = Number(row.isLock || 0)
  detailForm.isBatch = Number(row.isBatch || 0)
  detailForm.safetyStock = Number(row.safetyStock || 0)
  detailForm.descs = row.descs || ''
  detailForm.materialImg = row.materialImg || ''
  
  detailDialogVisible.value = true
}

// 修改搜索方法
const handleSearch = async () => {
  pagination.currentPage = 1
  await loadTableData()
}

// 修改重置搜索方法
const handleReset = async () => {
  searchForm.materialCode = ''
  searchForm.materialName = ''
  pagination.currentPage = 1
  await loadTableData()
}

// 处理页码改变
const handleCurrentChange = (val) => {
  console.log('当前页:', val)
  pagination.currentPage = val
  loadTableData()
}

// 处理首页点击
const handleFirstPage = () => {
  if (pagination.currentPage !== 1) {
    pagination.currentPage = 1
    loadTableData()
  }
}

// 处理上一页点击
const handlePrevPage = () => {
  if (pagination.currentPage > 1) {
    pagination.currentPage--
    loadTableData()
  }
}

// 处理下一页点击
const handleNextPage = () => {
  if (pagination.currentPage < totalPages.value) {
    pagination.currentPage++
    loadTableData()
  }
}

// 处理尾页点击
const handleLastPage = () => {
  if (pagination.currentPage !== totalPages.value) {
    pagination.currentPage = totalPages.value
    loadTableData()
  }
}

// 处理页码跳转
const handleJumpPage = () => {
  const page = parseInt(jumpPage.value)
  const maxPage = Math.ceil(pagination.total / pagination.pageSize)
  
  if (page && page > 0 && page <= maxPage) {
    pagination.currentPage = page
    loadTableData()
  }
  
  // 清空输入框，显示当前页码作为placeholder
  jumpPage.value = ''
}

// 处理修改按钮点击
const handleEdit = (row) => {
  editForm.id = Number(row.id || 0)
  editForm.materialCode = row.materialCode || ''
  editForm.materialName = row.materialName || ''
  editForm.specification = row.specification || ''
  editForm.flats = row.flats || ''
  editForm.flatsMaterial = row.flatsMaterial || ''  // 这里保存ID值
  editForm.isHighValue = Number(row.isHighValue || 0)
  editForm.isLock = Number(row.isLock || 0)
  editForm.isBatch = Number(row.isBatch || 0)
  editForm.safetyStock = Number(row.safetyStock || 0)
  editForm.descs = row.descs || ''
  editForm.materialImg = row.materialImg || ''
  
  editDialogVisible.value = true
}

// 修改保存方法
const saveEditMaterialProduct = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    
    const submitData = {
      id: Number(editForm.id),
      materialCode: editForm.materialCode,
      materialName: editForm.materialName,
      specification: editForm.specification,
      flats: editForm.flats,
      flatsMaterial: editForm.flatsMaterial,
      isHighValue: Number(editForm.isHighValue),
      isLock: Number(editForm.isLock),
      isBatch: Number(editForm.isBatch),
      safetyStock: Number(editForm.safetyStock),
      descs: editForm.descs,
      materialImg: editForm.materialImg
    }
    
    const response = await http.post(API_ENDPOINTS.UPDATE_MATERIAL_PRODUCT, submitData)
    
    if (response.status === true) {
      ElMessage.success('修改成功')
      editDialogVisible.value = false
      await loadTableData()
    } else {
      throw new Error(response.message || '修改失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '修改失败，请检查数据格式')
  }
}

// 添加监听器来跟踪表单数据变化
watch(
  () => editForm,
  (newVal) => {
    console.log('编辑表单数据变化:', newVal)
  },
  { deep: true }
)

// 添加控制变量
const isSearchVisible = ref(true)
const columnDialogVisible = ref(false)

// 列显示控制相关
const showColumns = ref([
  { prop: 'materialName', label: '物料/产品名称' },
  { prop: 'specification', label: '规格型号' },
  { prop: 'flats', label: '单位' },
  { prop: 'flatsMaterial', label: '物料/产品' },
  { prop: 'isLock', label: '是否启用' },
  { prop: 'safetyStock', label: '是否设置安全库存' },
  { prop: 'createTime', label: '创建时间' },
])

const hideColumns = ref([
  { prop: 'materialCode', label: '物料/产品编码' },
])

const selectedShowColumns = ref([])
const selectedHideColumns = ref([])

const showSection = ref(false)
const hideSection = ref(false)

// 计算属性
const isShowIndeterminate = computed(() => {
  return selectedShowColumns.value.length > 0 && 
         selectedShowColumns.value.length < showColumns.value.length
})

const isHideIndeterminate = computed(() => {
  return selectedHideColumns.value.length > 0 && 
         selectedHideColumns.value.length < hideColumns.value.length
})

// 方法
const toggleSearch = () => {
  isSearchVisible.value = !isSearchVisible.value
}

const refreshPage = async () => {
  await loadTableData()
}

const showColumnDialog = () => {
  columnDialogVisible.value = true
}

const handleShowAllChange = (val) => {
  selectedShowColumns.value = val ? showColumns.value.map(col => col.prop) : []
  showSection.value = val
}

const handleHideAllChange = (val) => {
  selectedHideColumns.value = val ? hideColumns.value.map(col => col.prop) : []
  hideSection.value = val
}

const moveToHide = () => {
  const columnsToMove = selectedShowColumns.value.map(prop => {
    return showColumns.value.find(col => col.prop === prop)
  }).filter(Boolean)

  hideColumns.value = [...hideColumns.value, ...columnsToMove]
  showColumns.value = showColumns.value.filter(col => !selectedShowColumns.value.includes(col.prop))
  selectedShowColumns.value = []
  showSection.value = false
}

const moveToShow = () => {
  const columnsToMove = selectedHideColumns.value.map(prop => {
    return hideColumns.value.find(col => col.prop === prop)
  }).filter(Boolean)

  showColumns.value = [...showColumns.value, ...columnsToMove]
  hideColumns.value = hideColumns.value.filter(col => !selectedHideColumns.value.includes(col.prop))
  selectedHideColumns.value = []
  hideSection.value = false
}

// 修改列显示控制相关的方法
const handleColumnTreeNodeClick = (data) => {
  console.log('列显示设置 - 点击的树节点:', data)
  // 在表格数据中隐藏对应分类的数据
  const hideCategory = (categoryId) => {
    tableData.value = tableData.value.filter(item => 
      String(item.flatsMaterial) !== String(categoryId)
    )
  }
  hideCategory(data.id)
}

// 添加一个计算属性来获取分类的完整路径
const getCategoryFullPath = (categoryId) => {
  if (!categoryId) return ''
  
  const path = []
  const findPath = (categories, targetId) => {
    for (const category of categories) {
      if (String(category.id) === String(targetId)) {
        path.push(category.label)
        return true
      }
      if (category.children && category.children.length > 0) {
        if (findPath(category.children, targetId)) {
          path.unshift(category.label)
          return true
        }
      }
    }
    return false
  }
  
  findPath(categoryTreeData.value, categoryId)
  return path.join(' / ')
}

onMounted(async () => {
  try {
    await Promise.all([
      getCategoryTree(),
      materialProductList()
    ])
  } catch (error) {
    handleApiError(error, '初始化数据失败')
  }
})
</script>

<style scoped>
.material-product-container {
  display: flex;
  height: 100%;
  gap: 20px;
  padding: 20px;
}

.left-tree {
  width: 250px;
  border-right: 1px solid #dcdfe6;
  padding-right: 20px;
}

.search-input {
  margin-bottom: 20px;
}

.right-content {
  flex: 1;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree) {
  background: none;
}

.el-switch {
  margin: 0 4px;
}
.safety-stock-tag {
  min-width: 40px;
}
.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
.auto-generate-switch {
  display: flex;
  align-items: center;
  margin-left: 10px;
}
.auto-generate-text {
  display: flex;
  flex-direction: row;
  margin-left: 5px;
  font-size: 14px;
  color: #606266;
}
.auto-generate-text span {
  margin-right: 2px;
}

:deep(.el-select-dropdown__item) {
  padding-left: 20px;
}

:deep(.el-select-group__wrap:not(:last-of-type)) {
  padding-bottom: 0;
}

:deep(.el-select-group__title) {
  padding-left: 10px;
  font-weight: bold;
  color: #606266;
}

:deep(.el-select-group) .el-select-dropdown__item {
  padding-left: 30px;
}

:deep(.el-select-group .el-select-group) .el-select-dropdown__item {
  padding-left: 40px;
}

:deep(.el-tree-select) {
  width: 100%;
}

:deep(.el-select-dropdown__item) {
  padding: 0 8px;
}

:deep(.el-tree-node__content) {
  height: 34px;
  line-height: 34px;
}

:deep(.el-tree-node__expand-icon) {
  padding: 8px;
}

:deep(.el-tree) {
  min-width: 100%;
  display: inline-block !important;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.material-code-link {
  color: #409EFF;
  text-decoration: none;
  cursor: pointer;
}

.material-code-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 10px 0;
}

.total-text {
  margin-right: 15px;
  color: #606266;
}

.page-size-selector {
  margin-right: 15px;
}

.custom-pagination {
  display: flex;
  align-items: center;
  margin: 0 15px;
}

.page-btn {
  min-width: 32px;
  height: 32px;
  padding: 0 4px;
  margin: 0 4px;
  background-color: #f4f4f5;
  border: none;
  border-radius: 2px;
  color: #606266;
  cursor: pointer;
  font-size: 13px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-btn:hover:not(:disabled) {
  color: #409eff;
}

.page-btn:disabled {
  cursor: not-allowed;
  color: #c0c4cc;
}

.page-btn.active {
  background-color: #409eff;
  color: white;
}

.page-numbers {
  display: flex;
  align-items: center;
}

.page-jump {
  display: flex;
  align-items: center;
  margin-left: 15px;
}

.page-jump .text {
  color: #606266;
  font-size: 14px;
}

.page-jump .jump-input {
  width: 50px;
  margin: 0 8px;
}

.page-jump .jump-input :deep(.el-input__inner) {
  padding: 0 5px;
  text-align: center;
  height: 28px;
  line-height: 28px;
}

:deep(.el-select .el-input__inner) {
  padding-right: 25px;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
}

.custom-button {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
}

.custom-button .el-icon {
  margin-right: 4px;
}

:deep(.el-button.custom-button.is-plain:focus),
:deep(.el-button.custom-button.is-plain:hover) {
  color: var(--el-button-hover-text-color);
  border-color: var(--el-button-hover-border-color);
  background-color: var(--el-button-hover-bg-color);
  outline: none;
}

:deep(.el-button.custom-button.is-plain) {
  --el-button-bg-color: transparent;
  --el-button-border-color: var(--el-button-text-color);
}

.control-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-bottom: 16px;
}

.column-dialog-content {
  min-height: 400px;
  padding: 16px;
}

:deep(.el-tree) {
  width: 100%;
  background: none;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>